import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution947 {
    public int removeStones(int[][] stones) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int[] stone : stones) {
            if (!map.containsKey(stone[0]+10000)){
                map.put(stone[0]+10000,stone[0]+10000);
            }
            if (!map.containsKey(stone[1])){
                map.put(stone[1],stone[1]);
            }
            int x=find(map,stone[0]+10000);
            int y=find(map,stone[1]);
            if (x!=y){
                map.put(x,y);
            }
        }
        Set<Integer> set=new HashSet<>();
        int ans=0;
        for (int[] stone : stones) {
            if (!set.contains(find(map,stone[0]+10000))){
                ans++;
                set.add(find(map,stone[0]+10000));
            }
        }
        return stones.length-ans;
    }

    int find(Map<Integer,Integer> map,int t){
        while (t!=map.get(t)){
            t=map.get(t);
        }
        return t;
    }

    public static void main(String[] args) {
        System.out.println(new Solution947().removeStones(new int[][]{{0,0},{0,2},{1,1},{2,0},{2,2}}));
    }
}
